// pages/goods_detail/index.js
import {request} from "../../request/index.js";
import regeneratorRuntime, { async } from "../../libs/runtime/runtime";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj:{},
    isCollect:false
  },
  GoodsInfo:{},

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    let pages=getCurrentPages();
    let currentPage=pages[pages.length-1];
    let options=currentPage.options;
    const {goods_id}=options;
    this.getGoodsDetail(goods_id);
   
  },
  //获取商品详情数据
  async getGoodsDetail(goods_id){
    const res=await request({url:'/goods/detail',data:{goods_id}});
    this.GoodsInfo=res;
     // 获取缓存中的商品收藏的数组
     let collect=wx.getStorageSync('collect')||[];
     //判断当前商品是否被收藏
     let isCollect=collect.some(v=>v.goods_id===this.GoodsInfo.goods_id);
    this.setData({
      goodsObj:{
        goods_name:res.goods_name,
        goods_price:res.goods_price,
        goods_introduce:res.goods_introduce,
        pics:res.pics
      },
      isCollect
    })
  },
  //点击轮播图放大预览
  handlePrevewImage(e){
    //1 先构造要预览的图片数组
    const urls=this.GoodsInfo.pics.map(v=>v.pics_mid);
    const current=e.currentTarget.dataset.url;
    wx.previewImage({
      urls,
      current
    })
  },
  //点击加入购物车
  handleCartAdd(){
    //1 获取缓存中购物车数组
    let cart=wx.getStorageSync("cart")||[];
    //2 判断商品对象是否存在于购物车数组中
    let index=cart.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id);
    if(index===-1){
      this.GoodsInfo.num=1;
      this.GoodsInfo.checked=true;
      cart.push(this.GoodsInfo);
    }else{
      cart[index].num++;
    }
    //3.把购物车重新添加回缓存中
    wx.setStorageSync('cart', cart);
    wx.showToast({
      title: '加入成功',
      icon:'success',
      mask:true
    })
  },
  handleCollect(){
    let isCollect=false;
    //获取缓存中的商品收藏数组
    let collect=wx.getStorageSync('collect')||[];
    //判断该商品是否被收藏过
    let index =collect.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id);
    //当index!=-1表示已经收藏过
    if(index!==-1){
      collect.splice(index,1);
      isCollect=false;
      wx.showToast({
        title:"取消成功",
        icon:"success",
        mask:true,
      });
    }else{
      collect.push(this.GoodsInfo);
      isCollect=true;
      wx.showToast({
        title:"收藏成功",
        icon:"success",
        mask:true,
      });
    }
    //把数组存入到缓存中
    wx.setStorageSync('collect', collect)
    //修改data中的属性 isCollect
    this.setData({
      isCollect
    })

  }
})